MySQL top count({column}) with a limit

Posted by Josh K on Stack Overflow See other posts from Stack Overflow or by Josh K
Published on 2010-04-29T02:10:18Z Indexed on 2010/04/29 2:17 UTC
Read the original article Hit count: 371

Filed under:
|
|
|
|

I have a table with an ip address column. I would like to find the top five addresses which are listed.

Right now I'm planning it out the following:

  1. Select all distinct ip addresses
  2. Loop through them all saying count(id) where IP='{ip}' and storing the count
  3. List the top five counts.

Downsides include what if I have 500 ip addresses. That's 500 queries I have to run to figure out what are the top five.

I'd like to build a query like so

select ip from table where 1 order by count({distinct ip}) asc limit 5

© Stack Overflow or respective owner

Related posts about mysql

Related posts about query